<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>结算单</title>
    <style>
        /* 基础样式重置 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: #f5f7fa;
            color: #333;
            line-height: 1.6;
        }
        
        .bill-container {
            min-height: 100vh;
            background: #f5f7fa;
            padding: 5px;
            overflow-x: hidden;
            max-width: 480px;
            margin: 0 auto;
        }
        
        /* 页面标题 */
        .page-header {
            text-align: center;
            margin-bottom: 10px;
            background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
            padding: 10px 12px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(103, 194, 58, 0.2);
        }
        
        .page-title {
            color: white;
            font-size: 18px;
            font-weight: bold;
            margin: 0;
        }
        
        /* 账单列表 */
        .bill-list {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        
        .bill-card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            transition: all 0.3s ease;
        }
        
        .bill-card:hover {
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
            transform: translateY(-2px);
        }
        
        /* 账单头部 */
        .bill-header {
            padding: 10px 12px;
            background: #f8f9fa;
            border-bottom: 1px solid #e9ecef;
        }
        
        .merchant-name {
            font-size: 16px;
            font-weight: bold;
            color: #2c3e50;
            margin: 0 0 5px 0;
        }
        
        /* 企业信息 */
        .enterprise-info {
            padding: 10px 12px;
            border-bottom: 1px solid #e9ecef;
        }
        
        .info-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
            flex-wrap: wrap;
        }
        
        .info-row:last-child {
            margin-bottom: 0;
        }
        
        .label {
            font-weight: 600;
            color: #495057;
            min-width: auto;
            margin-right: 8px;
            font-size: 12px;
            flex-shrink: 0;
        }
        
        .value {
            color: #212529;
            font-size: 12px;
            flex: 1;
            text-align: right;
        }
        
        /* 费用明细表格 */
        .bill-table {
            padding: 8px 5px;
            overflow-x: hidden;
        }
        
        .fee-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 12px;
            table-layout: fixed;
            min-width: 100%;
        }
        
        .fee-table th,
        .fee-table td {
            padding: 6px 4px;
            text-align: left;
            border: 1px solid #dee2e6;
            word-wrap: break-word;
            overflow: hidden;
            line-height: 1.3;
            font-size: 9px;
        }
        
        .fee-table th {
            background: #f8f9fa;
            font-weight: 600;
            color: #495057;
        }
        
        .fee-table td {
            color: #212529;
        }
        
        .fee-type {
            font-weight: 600;
            word-break: break-all;
        }
        
        .fee-details {
            word-break: break-all;
        }
        
        .fee-amount {
            text-align: right;
            font-weight: 600;
            color: #e74c3c;
        }
        
        /* 账单汇总 */
        .bill-summary {
            padding: 10px 12px;
            background: #f8f9fa;
            border-top: 2px solid #67c23a;
        }
        
        .summary-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
        }
        
        .summary-row:last-child {
            margin-bottom: 0;
        }
        
        .total-amount {
            font-size: 12px;
            font-weight: bold;
            color: #e74c3c;
        }
        
        .payee {
            font-weight: 600;
            color: #495057;
            font-size: 12px;
        }
        
        
        /* 空状态样式 */
        .empty-state {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 40px 20px;
            text-align: center;
            color: #909399;
        }
        
        .empty-state p {
            margin: 0 0 8px 0;
            font-size: 14px;
        }
        
        .empty-tip {
            font-size: 12px;
            color: #c0c4cc;
        }
        
        .hidden {
            display: none !important;
        }
        
        /* 提示 */
        .message-toast {
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: #fff;
            border: 1px solid #e4e7ed;
            border-radius: 4px;
            padding: 12px 20px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            z-index: 9999;
            font-size: 14px;
            color: #606266;
            max-width: 400px;
            word-wrap: break-word;
            animation: messageSlideIn 0.3s ease-out;
        }
        
        .message-toast.success {
            background: #f0f9ff;
            border-color: #67c23a;
            color: #67c23a;
        }
        
        .message-toast.warning {
            background: #fdf6ec;
            border-color: #e6a23c;
            color: #e6a23c;
        }
        
        .message-toast.error {
            background: #fef0f0;
            border-color: #f56c6c;
            color: #f56c6c;
        }
        
        @keyframes messageSlideIn {
            from {
                opacity: 0;
                transform: translateX(-50%) translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateX(-50%) translateY(0);
            }
        }
        
    </style>
</head>
<body>
    <div class="bill-container">
        <!-- 页面标题 -->
        <div class="page-header">
            <h2 class="page-title">结算单</h2>
        </div>
        <!-- 账单列表 -->
        <div class="bill-list" id="billList">
        </div>
        <!-- 空状态 -->
        <div class="empty-state hidden" id="emptyState">
            <p>暂无结算单数据</p>
            <p class="empty-tip">请从结算单管理页面点击"分享"按钮查看详情</p>
        </div>
    </div>

    <script>
        // 全局变量
        let billData = null; 
        // API基础路径配置 
        const API_BASE_PATH = (() => {
            // 开发环境使用Vite代理
            if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
                return window.location.origin + '/base-api';
            }
            // 生产环境直接使用当前域名
            return window.location.origin;
        })();
        
        async function fetchAPI(url, options = {}) {
            const possiblePaths = [
                url,
                url.replace('/base-api', ''),
                url.replace(window.location.origin, window.location.origin + '/api'),
            ];
            
            for (let i = 0; i < possiblePaths.length; i++) {
                try {
                    const response = await fetch(possiblePaths[i], options);
                    
                    if (response.ok) {
                        const contentType = response.headers.get('content-type');
                        if (contentType && contentType.includes('application/json')) {
                            return response;
                        }
                    }
                } catch (error) {
                }
            }
            
            throw new Error('所有API路径都失败了');
        }
        function showMessage(message, type = 'info') {
            const existingMessage = document.querySelector('.message-toast');
            if (existingMessage) {
                existingMessage.remove();
            }
            
            const messageEl = document.createElement('div');
            messageEl.className = `message-toast ${type}`;
            messageEl.textContent = message;
            
            document.body.appendChild(messageEl);
            
            setTimeout(() => {
                if (messageEl.parentNode) {
                    messageEl.remove();
                }
            }, 3000);
        }
        
        function getToken() {
            return localStorage.getItem('token');
        }
        
        function getUsageUnit(objectType) {
            switch (objectType) {
                case '房租':
                    return '平方米';
                case '电表':
                    return 'kW·h';
                case '水表':
                    return 't';
                default:
                    return '';
            }
        }
        
        async function loadBillData() {
            try {
                const urlParams = new URLSearchParams(window.location.search);
                const billId = urlParams.get('billId');
                const from = urlParams.get('from');
                const enterpriseId = urlParams.get('enterpriseId');
                const shareToken = urlParams.get('token');
                
                if (billId && from === 'billTotal') {
                    // 优先使用URL中的token，其次使用localStorage中的token
                    const token = shareToken || getToken();
                    if (!token) {
                        showMessage('请先登录系统后再访问此页面，或使用有效的分享链接', 'warning');
                        showEmptyState('请先登录系统后再访问此页面，或使用有效的分享链接');
                        return;
                    }
                    
                    const response = await fetchAPI(`${API_BASE_PATH}/mrs/settle-bill-total/detail/${billId}`, {
                        method: 'GET',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': token
                        }
                    });
                    
                    const result = await response.json();
                    
                    if ((result.code === 0 || result.code === 200) && result.success && result.data) {
                        const data = result.data;
                        
                        const billData = {
                            id: data.id,
                            merchantName: data.tenantName || '商户名称',
                            enterpriseName: data.enterpriseName || '企业名称',
                            rentalArea: data.rentalArea ? Number(data.rentalArea) : undefined,
                            email: data.email || '无',
                            location: data.companyAddress || '企业地址',
                            period: data.billPeriod || '账期',
                            feeDetails: (data.detailList || []).map(item => ({
                                type: item.groupName || '费用项目',
                                details: `${item.currentUsage || 0}${getUsageUnit(item.objectType)} / ${item.unitPrice || 0}元/${getUsageUnit(item.objectType)} / ${item.allocationRatio || 100}%`,
                                amount: item.feeAmount || 0
                            })),
                            totalAmount: data.totalFeeAmount || 0
                        };
                        
                        renderBillData(billData);
                    } else {
                        showMessage('获取结算单数据失败，请稍后重试', 'error');
                        showEmptyState();
                    }
                } else {
                    showEmptyState();
                }
            } catch (error) {
                showMessage('加载数据失败，请稍后重试', 'error');
                showEmptyState();
            }
        }
        
        function renderBillData(data) {
            const billListElement = document.getElementById('billList');
            const emptyStateElement = document.getElementById('emptyState');
            
            const billHtml = `
                <div class="bill-card">
                    <!-- 账单头部 -->
                    <div class="bill-header">
                        <div class="merchant-info">
                            <h3 class="merchant-name">${data.merchantName || '商户名称'}</h3>
                        </div>
                    </div>

                    <!-- 企业信息 -->
                    <div class="enterprise-info">
                        <div class="info-row">
                            <span class="label">入驻企业:</span>
                            <span class="value">${data.enterpriseName || '企业名称'}</span>
                        </div>
                        <div class="info-row">
                            <span class="label">租凭面积:</span>
                            <span class="value">${data.rentalArea ? data.rentalArea + '㎡' : '无数据'}</span>
                        </div>
                        <div class="info-row">
                            <span class="label">企业邮箱:</span>
                            <span class="value">${data.email || '无'}</span>
                        </div>
                        <div class="info-row">
                            <span class="label">地点位置:</span>
                            <span class="value">${data.location || '企业地址'}</span>
                        </div>
                        <div class="info-row">
                            <span class="label">账期:</span>
                            <span class="value">${data.period || '账期'}</span>
                        </div>
                    </div>

                    <!-- 费用明细表格 -->
                    <div class="bill-table">
                        <table class="fee-table">
                            <thead>
                                <tr>
                                    <th style="width: 20%">项目</th>
                                    <th style="width: 60%">当期用量/计费单价/分摊比例</th>
                                    <th style="width: 20%">金额</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${(data.feeDetails || []).map(item => `
                                    <tr>
                                        <td class="fee-type">${item.type || '费用项目'}</td>
                                        <td class="fee-details">${item.details || ''}</td>
                                        <td class="fee-amount">¥${(item.amount || 0).toLocaleString()}</td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    </div>

                    <!-- 账单汇总 -->
                    <div class="bill-summary">
                        <div class="summary-row">
                            <span class="label">合计:</span>
                            <span class="total-amount">¥${(data.totalAmount || 0).toLocaleString()}</span>
                        </div>
                        <div class="summary-row">
                            <span class="label">收款方:</span>
                            <span class="payee">${data.merchantName || '商户名称'}</span>
                        </div>
                    </div>
                </div>
            `;
            
            billListElement.innerHTML = billHtml;
            emptyStateElement.classList.add('hidden');
        }
        
        function showEmptyState(customMessage) {
            const billListElement = document.getElementById('billList');
            const emptyStateElement = document.getElementById('emptyState');
            
            billListElement.innerHTML = '';
            emptyStateElement.classList.remove('hidden');
            
            if (customMessage) {
                const emptyStateContent = emptyStateElement.querySelector('.empty-state');
                if (emptyStateContent) {
                    emptyStateContent.innerHTML = `
                        <p>${customMessage}</p>
                        <p class="empty-tip">请从结算单管理页面点击"分享"按钮查看详情</p>
                    `;
                }
            }
        }
        
        document.addEventListener('DOMContentLoaded', function() {
            loadBillData();
        });
    </script>
</body>
</html>
